// components/Console/SerialConsole.tsx
import React, { useEffect, useRef, useState } from 'react';
import { consoleService } from '../../services/console';

interface SerialConsoleProps {
  connection: string;
  domainName: string;
  className?: string;
}

const SerialConsole: React.FC<SerialConsoleProps> = ({
  connection,
  domainName,
  className = ''
}) => {
  const terminalRef = useRef<HTMLDivElement>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [output, setOutput] = useState<string[]>([]);

  useEffect(() => {
    let ws: WebSocket | null = null;

    const connectSerial = async () => {
      try {
        // 获取串口信息
        const serialInfo: any = await consoleService.getSerialInfo(connection, domainName);

        if (!serialInfo.host || !serialInfo.port) {
          throw new Error('Serial connection information not available');
        }

        // 创建WebSocket连接
        const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
        ws = new WebSocket(`${protocol}//${window.location.host}/api/v1/console/serial?connection=${connection}&name=${domainName}&token=${serialInfo.token}`);

        ws.onopen = () => {
          setLoading(false);
          setError(null);
        };

        ws.onmessage = (event) => {
          setOutput(prev => [...prev, event.data]);
        };

        ws.onerror = (err) => {
          setError('Serial console connection error');
          console.error('Serial console error:', err);
        };

        ws.onclose = () => {
          setError('Serial console connection closed');
        };

      } catch (err) {
        setError(err instanceof Error ? err.message : 'Failed to connect to serial console');
        setLoading(false);
      }
    };

    if (connection && domainName) {
      connectSerial();
    }

    return () => {
      // 清理连接
      if (ws) {
        // 确保 ws 是 WebSocket 类型再调用 close 方法
        if ('close' in ws && typeof (ws as WebSocket).close === 'function') {
          (ws as WebSocket).close();
        }
      }
    };
  }, [connection, domainName]);

  if (loading) {
    return (
      <div className={`flex items-center justify-center h-64 ${className}`}>
        <div className="text-center">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-purple-500 mx-auto mb-4"></div>
          <p className="text-gray-500">Connecting to serial console...</p>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className={`flex items-center justify-center h-64 ${className}`}>
        <div className="text-center">
          <div className="text-red-500 mb-4">
            <svg className="w-12 h-12 mx-auto" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
            </svg>
          </div>
          <p className="text-red-500 mb-4">{error}</p>
          <p className="text-sm text-gray-500">
            Serial console requires xterm.js library integration.
          </p>
          <p className="text-sm text-gray-500">
            Connection info: Host and Port available from API
          </p>
        </div>
      </div>
    );
  }

  return (
    <div className={`relative ${className}`}>
      <div className="bg-black rounded-lg overflow-hidden">
        <div className="p-4 bg-gray-800 text-white text-sm font-mono">
          <div className="flex items-center justify-between mb-2">
            <span>Serial Console - {domainName}</span>
            <span className="text-green-400">✓ Connected</span>
          </div>
          <div className="text-xs text-gray-400">
            <p>Serial console integration placeholder</p>
            <p>Install xterm.js for full functionality</p>
          </div>
        </div>

        {/* !输出: */}
        <div className="h-96 bg-black p-4 overflow-y-auto font-mono text-sm">
          <div className="text-green-400">
            {output.map((line, index) => (
              <div key={index} className="mb-1">
                {line}
              </div>
            ))}
          </div>
          <div className="text-green-400 mt-2">
            <span className="animate-pulse">_</span>
          </div>
        </div>
      </div>

      {/* 隐藏的终端divC 用于xterm.js */}
      <div ref={terminalRef} className="hidden" />
    </div>
  );
};

export default SerialConsole;